package com.sikadwafastdaisfondturbo.pretloan.ui.process.activity

import android.view.View
import androidx.camera.core.AspectRatio
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageCapture
import androidx.camera.core.ImageCaptureException
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.core.content.ContextCompat
import com.sikadwafastdaisfondturbo.pretloan.app.App
import com.sikadwafastdaisfondturbo.pretloan.databinding.ActivityCameraOcrBinding
import com.sikadwafastdaisfondturbo.pretloan.pro.ProActivity
import com.sikadwafastdaisfondturbo.pretloan.utils.BarUtils
import com.sikadwafastdaisfondturbo.pretloan.utils.config.Configs
import com.sikadwafastdaisfondturbo.pretloan.utils.event.EventType
import com.sikadwafastdaisfondturbo.pretloan.utils.gilde.ImageUtil
import com.sikadwafastdaisfondturbo.pretloan.utils.imagecovert.ImageConvert
import com.sikadwafastdaisfondturbo.pretloan.utils.log.HHLog
import java.io.File
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

/**
 * Sikadwa
 * @Author wwdeng
 * @CreateTime: 2024/5/29 18:06
 * @Annotation：驾驶证、护照、身份证拍照
 */
class CameraOcrActivity: ProActivity() {
    private var _binding: ActivityCameraOcrBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "Cannot Face camera binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )

    private lateinit var cameraExecutor: ExecutorService
    private var imageCapture: ImageCapture? = null
    private var imgUsePath = ""
    override fun getRootView(): View {
        _binding = ActivityCameraOcrBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initView() {
        BarUtils.setStatusBarLightMode(this, false)
        _binding?.titleLayout?.setPadding(0,BarUtils.getStatusBarHeight(),0,0)

        cameraExecutor = Executors.newSingleThreadExecutor()
        startCamera()

        _binding?.imgLang?.visibility = View.GONE
        if (Configs.isTanzania()){
            _binding?.imgLang?.visibility = View.VISIBLE
        }
    }

    override fun initListener() {
        _binding?.imgBack?.setOnClickListener {
            finish()
        }
        _binding?.imgLang?.setOnClickListener {
            showSikadwaProLangDialog("OcrCamera Page", onCheckSuccess = {

            })
        }

        _binding?.imgKefu?.setOnClickListener {
            showKefuDialog("OcrCamera Page")
            addEvent(EventType.CLICK.CLICK_CUSTOMER,"OcrCamera Page")
        }

        //拍照
        _binding?.imgTakeCamera?.setOnClickListener {
            addEvent(EventType.CLICK.CLICK_CAMERA_TAKE_PHOTO,"OcrCamera Page")
            takeFilePhoto()
        }

        //重拍
        _binding?.remakeLayout?.setOnClickListener {
            addEvent(EventType.CLICK.CLICK_STEP_OCR_UPLOAD_RETAKE,"OcrCamera Page")
            showTakeView()
        }

        //使用
        _binding?.usePhotoLayout?.setOnClickListener {
            addEvent(EventType.CLICK.CLICK_STEP_OCR_UPLOAD_USE_PHOTO,"OcrCamera Page")
            val intent = intent
            intent.putExtra("imgLocalPath",imgUsePath)
            setResult(RESULT_OK,intent)
            finish()
        }
    }

    override fun initData() {
    }

    /**
     * 打开相机预览
     */
    private fun startCamera() {
        showTakeView()
        val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
        cameraProviderFuture.addListener(Runnable {
            val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()
            val preview = Preview.Builder()
                .setTargetAspectRatio(AspectRatio.RATIO_16_9)
                .build()
                .also {
                    it.setSurfaceProvider(_binding?.carmeraView?.surfaceProvider)
                }
            imageCapture = ImageCapture.Builder().build()
            //打开后置摄像头
            val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA
            try {
                cameraProvider.unbindAll()
                cameraProvider.bindToLifecycle(this, cameraSelector, preview,imageCapture)
            } catch(exc: Exception) {
            }
        }, ContextCompat.getMainExecutor(this))
    }

    /**
     * 拍照并保存到本地
     */
    private fun takeFilePhoto(){
        imageCapture?.let {
            //创建文件
//            val filePath = Environment.getExternalStorageDirectory().toString() + File.separator + "DCIM/Camera/";
            val filePath = App.instance().filesDir.absolutePath
            val outputFile = File(filePath,"${System.currentTimeMillis()}.jpg")
            if (!outputFile.exists()){
                outputFile.mkdir()
            }
            //创建输出选项对象
            val metadata = ImageCapture.Metadata()
            metadata.isReversedHorizontal = true
            //创建文件
            val outputFileOptions = ImageCapture.OutputFileOptions.Builder(outputFile).setMetadata(metadata).build()
            //开始拍照
            it.takePicture(outputFileOptions,ContextCompat.getMainExecutor(this),object : ImageCapture.OnImageSavedCallback{
                override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
                    val imgUri = outputFileResults.savedUri

                    HHLog.e("take photo complete>>>>>>>${imgUri?.path}")
                    // 图片处理
                    ImageConvert.covert(context = this@CameraOcrActivity, uri = imgUri) { localPath, bitmap ->
                        if (localPath != null){
                            imgUsePath = localPath
                            HHLog.e("imageConvert success>>>>>>>$localPath")
                            showCompleteView()
                        }
                    }
                }

                override fun onError(exception: ImageCaptureException) {
                    HHLog.e("拍照失败>>>>>>>${exception.message}")
                }
            })
        }
    }

    /**
     * 显示拍照样式
     */
    private fun showTakeView(){
        _binding?.let { binding ->
            binding.imgPreview.visibility = View.GONE
            binding.imgTakeCamera.visibility = View.VISIBLE
            binding.remakeLayout.visibility = View.INVISIBLE
            binding.usePhotoLayout.visibility = View.INVISIBLE
        }
    }

    /**
     * 显示拍照完成页面
     */
    private fun showCompleteView(){
        _binding?.let { binding ->
            ImageUtil.instance?.loadImageUrl(this@CameraOcrActivity,binding.imgPreview,imgUsePath)
            binding.imgPreview.visibility = View.VISIBLE
            binding.imgTakeCamera.visibility = View.INVISIBLE
            binding.remakeLayout.visibility = View.VISIBLE
            binding.usePhotoLayout.visibility = View.VISIBLE
        }
    }

    override fun onStart() {
        super.onStart()
        addEvent(EventType.PAGE.PAGE_STEP_OCR_CAMERA_START,"")
    }

    override fun onDestroy() {
        super.onDestroy()
        _binding = null
        addEvent(EventType.PAGE.PAGE_STEP_OCR_CAMERA_END,"")
        if (::cameraExecutor.isInitialized){
            cameraExecutor.shutdown()
        }
    }
}